package com.css.fxfzaqbz.modules.assessplot.controller;


import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.modules.assessplot.vo.DistrictVO;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Properties;

@Slf4j
@Component
public class YpgRestManager {

    @Autowired
    private RestTemplate restTemplate;

    private static final String GEOGRAPHIC_LOCATION_BY_RANGE = "preAssessResult/seiCapCalculationToAb";

    /**
     * 获取基础请求路径
     *
     * @return
     */
    private static String getBaseUrl(String apiUrl) throws Exception {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String ypgRestUrl = configGroup.getProperty("ypgRestTemplateUrl");
        if (StringUtils.isBlank(ypgRestUrl)) {
            throw new Exception("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(ypgRestUrl, "/")) {
            ypgRestUrl += "/";
        }
        return ypgRestUrl + apiUrl;
    }

    /**
     * 构建一个基础的请求头
     *
     * @return
     */
    private static HttpHeaders buildBaseHeaders() {
        HttpHeaders headers = new HttpHeaders();
       // headers.add("Authorization", "dzzhfxpgyqhxt");
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    public JSONObject getGeographicLocationByRange(DistrictVO range){
        long startTime = System.currentTimeMillis();
        HttpEntity<DistrictVO> entity = new HttpEntity<>(range, buildBaseHeaders());
        String url = null;
        try {
            url = getBaseUrl(GEOGRAPHIC_LOCATION_BY_RANGE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            // ResponseEntity<JsonObject> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, JsonObject.class);

            long endTime = System.currentTimeMillis();
            log.info("远程调用用时:{}", (endTime - startTime) + "ms");
//            return body;
            return body;
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }
}
